package com.example.unruly_zhao.mopaide.table;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.view.VerticalViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.unruly_zhao.mopaide.R;
import com.example.unruly_zhao.mopaide.main.Activity_HomePage;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment1;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment10;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment11;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment12;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment2;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment3;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment4;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment5;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment6;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment7;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment8;
import com.example.unruly_zhao.mopaide.tabfragment.PageFragment9;
import com.github.zl.changetablayout.ChangeTabLayout;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItem;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems;

public class Activity_TabLayouyt extends AppCompatActivity implements View.OnClickListener {

    private String TAG = "Activity_TabLayouyt";

    private VerticalViewPager mViewPager;

    private ChangeTabLayout mTabLayout;


    private String[] title = new String[]{
            "电影娱乐", "新闻头条", "娱乐八卦", "热门游戏",
            "本店优惠", "小游戏", "在线学习", "轻松视屏", "动漫阅读",
            "经典小说", "儿童教育", "热门应用", "全部应用"
    };

    private int[] icon = new int[]{
            R.drawable.iv_movie_press,
            R.drawable.iv_news_press,
            R.drawable.iv_yule_press,
            R.drawable.iv_ganme_normal,
            R.drawable.iv_youhui_press,
            R.drawable.iv_xiaoyouxi_press,
            R.drawable.iv_dongmanyuedu_press,
            R.drawable.iv_shipin_press,
            R.drawable.dm,
            R.drawable.iv_xiaoshuo_normal,
            R.drawable.iv_children_normal,
            R.drawable.yy, R.drawable.yy
    };

    private FragmentPagerItems pages;
    private WebView tencent_webview;
    private ImageView mImgs_back;
    private WebSettings settings;
    private EditText mEditText_shuru;
    private ImageView mImgs_refresh;
    private ImageView mImgs_advance;


    private RelativeLayout.LayoutParams mLayoutParams; // webview 布局设置大小

    /**
     * 5分钟不操作返回主界面
     */
    private BackMain backMain, backMain2;
    private boolean mFlag;
    private Handler mHandler = new Handler();
    private boolean mFlags;


    private ImageView mImgs_out_screen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /*
         * 隐藏软键盘(功能键)
         */
        getWindow().getDecorView().setSystemUiVisibility(

                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_tablayout);

        initial_widget(); //初始化布局

       /* // 判断启动页是否为当前任务栈的根Activity，如果不是根Activity则finish掉
        if (!isTaskRoot()) {
            finish();
            return;
        }*/

        // 后退键
        mImgs_back = (ImageView) findViewById(R.id.tab_imgs_back);

        // 关闭当前界面返回上一界面
        mImgs_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                tencent_webview.goBack();
            }
        });

        // 前进键
        mImgs_advance = (ImageView) findViewById(R.id.tab_imgs_advance);

        mImgs_advance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                tencent_webview.goForward();
            }
        });


        pages = new FragmentPagerItems(this);

        mViewPager.setOffscreenPageLimit(title.length);

      /*  for (String titleResId : title) {
            pages.add(FragmentPagerItem.of(titleResId, PageFragment.class));

        }*/

        for (int i=0;i<title.length;i++){
            if (i==0){
                pages.add(FragmentPagerItem.of(title[i], PageFragment.class));
            }
            else if (i==1){
                pages.add(FragmentPagerItem.of(title[i], PageFragment1.class));
            }
            else if (i==2) {
                pages.add(FragmentPagerItem.of(title[i], PageFragment2.class));
            }
            else if (i==3) {
                pages.add(FragmentPagerItem.of(title[i], PageFragment3.class));
            }
            else if (i==4) {
                pages.add(FragmentPagerItem.of(title[i], PageFragment4.class));
            }
            else if (i==5) {
                pages.add(FragmentPagerItem.of(title[i], PageFragment5.class));
            }
            else if (i==6) {
                pages.add(FragmentPagerItem.of(title[i], PageFragment6.class));
            }
            else if (i==7) {
                pages.add(FragmentPagerItem.of(title[i], PageFragment7.class));
            }
            else if (i==8) {
                pages.add(FragmentPagerItem.of(title[i], PageFragment8.class));
            }
            else if (i==9) {
                pages.add(FragmentPagerItem.of(title[i], PageFragment9.class));
            }
            else if (i==10) {
                pages.add(FragmentPagerItem.of(title[i], PageFragment10.class));
            }
            else if (i==11) {
                pages.add(FragmentPagerItem.of(title[i], PageFragment11.class));
            }
            else if (i==12) {
                pages.add(FragmentPagerItem.of(title[i], PageFragment12.class));
            }
        }

        FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(getSupportFragmentManager(), pages);
        mViewPager.setAdapter(adapter);
        mTabLayout.setViewPager(mViewPager, icon, null);

        mTabLayout.setOnTabClickListener(new ChangeTabLayout.OnTabClickListener() {
            @Override
            public void onTabClicked(int position) {

                switch (position) {
                    case 0:
                        // 腾讯视屏
                        tencent_webview.loadUrl("https://v.qq.com/");

                        tencent_webview.setWebViewClient(new WebViewClient());

                        Toast.makeText(Activity_TabLayouyt.this, "1", Toast.LENGTH_LONG).show();

                        break;
                    case 1:
                        // 新闻头条
                        tencent_webview.loadUrl("https://www.toutiao.com");

                        tencent_webview.setWebViewClient(new WebViewClient());

                        Toast.makeText(Activity_TabLayouyt.this, "2", Toast.LENGTH_LONG).show();

                        break;
                    case 2:
                        // 娱乐八卦
                        tencent_webview.loadUrl("https://www.toutiao.com/ch/funny/");

                        tencent_webview.setWebViewClient(new WebViewClient());

                        break;
                    case 3:
                        // 热门游戏
                        tencent_webview.loadUrl("http://www.360kan.com/va/Z8EocnNw8pk3DT.html");

                        tencent_webview.setWebViewClient(new WebViewClient());

                        break;
                    case 4:
                        // 本店优惠  商家嵌套   在管理界面设置输入网址  因为每一个商家不一样 谁的商家谁输入自己的网址
                        tencent_webview.loadUrl("http://www.360kan.com/va/Z8EocnNw8pk3DT.html");

                        tencent_webview.setWebViewClient(new WebViewClient());

                        break;
                    case 5:
                        // 小游戏
                        tencent_webview.loadUrl("http://www.360kan.com/va/Z8EocnNw8pk3DT.html");

                        tencent_webview.setWebViewClient(new WebViewClient());

                        break;
                    case 6:
                        // 在线学习
                        tencent_webview.loadUrl("https://open.163.com");

                        tencent_webview.setWebViewClient(new WebViewClient());

                        break;
                    case 7:
                        //轻松视频
                        tencent_webview.loadUrl("http://m.toutiao.com/?channel=video ");

                        tencent_webview.setWebViewClient(new WebViewClient());

                        break;
                    case 8:
                        //动漫阅读
                        tencent_webview.loadUrl("http://ac.qq.com");

                        tencent_webview.setWebViewClient(new WebViewClient());

                        break;
                    case 9:
                        //经典小说
                        tencent_webview.loadUrl("http://m.qidian.com ");

                        tencent_webview.setWebViewClient(new WebViewClient());

                        break;
                    case 10:
                        //儿童教育
                        tencent_webview.loadUrl("http://kid.qq.com");

                        tencent_webview.setWebViewClient(new WebViewClient());

                        break;
                    case 11:
                        //热门应用
                        tencent_webview.loadUrl("https://www.hao123.com");

                        tencent_webview.setWebViewClient(new WebViewClient());

                        break;
                    case 12:

                        Intent intent = new Intent(Activity_TabLayouyt.this, Activity_HomePage.class);

                        startActivity(intent);


                        break;
                }
            }
        });

        init_CountDownTimer();

    }


    /**
     * 初始化控件
     */

    private void initial_widget() {

        mViewPager = (VerticalViewPager) this.findViewById(R.id.viewpager); //自定义viewpager

        mTabLayout = (ChangeTabLayout) this.findViewById(R.id.tabLayout);  // 自定义的tab

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);  // bar

        setSupportActionBar(toolbar);

        tencent_webview = (WebView) findViewById(R.id.tab_mv);  // WebView

        init_webview(); // 初始化webview加载视频

        mImgs_out_screen = (ImageView) findViewById(R.id.test_imgss);  // 退出全屏图标

        mImgs_out_screen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mLayoutParams = (RelativeLayout.LayoutParams) tencent_webview.getLayoutParams();

                mLayoutParams.height = 900;

                mLayoutParams.width = 1910;

                mLayoutParams.setMargins(226, 80, 0, 0);

                tencent_webview.setLayoutParams(mLayoutParams);

                mImgs_out_screen.setVisibility(View.GONE);

            }
        });

        mEditText_shuru = (EditText) findViewById(R.id.tab_et_shuru);  // 搜索框

        mImgs_refresh = (ImageView) findViewById(R.id.tab_imgs_refresh);  // 点击webview全屏模式

        mImgs_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                RelativeLayout.LayoutParams mLayoutParams = new RelativeLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

                tencent_webview.setLayoutParams(mLayoutParams);

                mImgs_out_screen.setVisibility(View.VISIBLE);

            }
        });

    }

    /**
     * TODO 点击事件
     */
    @Override
    public void onClick(View v) {

        switch (v.getId()) {

        }

    }

    /**
     * 加载视频
     */
    private void init_webview() {

        tencent_webview.loadUrl("https://v.qq.com/"); // 加载网址

        // 解决webview不能加载视频
        settings = tencent_webview.getSettings();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)

            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setAllowFileAccess(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setDatabaseEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setDefaultTextEncodingName("UTF-8");

    }


    public void pageScrolled(int page, int position, float positionOffset) {
        //TODO  tablayout滑动事件
        //mTabLayout.setPageScrolled(page, position, positionOffset);
    }

    /**
     * 点击返回上一层（WebView）
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (tencent_webview != null && tencent_webview.canGoBack()) {
                tencent_webview.goBack();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 实现功能5分钟不点击退回出界面
     */

    private void init_CountDownTimer() {

        // TODO: 2017/8/29 五分钟无人操作回主页面

        backMain = new BackMain(1000 * 60*60, 1000, Activity_TabLayouyt.this);

        backMain2 = new BackMain(1000 * 60*120, 1000, Activity_TabLayouyt.this);
    }

    @Override
    protected void onResume() {

        timeStart();
        super.onResume();

    }

    //region 无操作 返回主页

    private void timeStart() {

        new Handler(getMainLooper()).post(new Runnable() {

            @Override
            public void run() {

                backMain.start();

            }
        });
    }

    /**
     * 主要的方法，重写dispatchTouchEvent
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {
            //获取触摸动作，如果ACTION_UP，计时开始。
            case MotionEvent.ACTION_UP:
                backMain.start();
                break;
            //否则其他动作计时取消
            default:
                backMain.cancel();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onPause() {
        super.onPause();
        backMain.cancel();
    }

    class BackMain extends CountDownTimer {

        private Context context;

        /**
         * 参数 millisInFuture       倒计时总时间（如60S，120s等）
         * 参数 countDownInterval    渐变时间（每次倒计1s）
         */
        public BackMain(long millisInFuture, long countDownInterval, Context context) {
            super(millisInFuture, countDownInterval);
            this.context = context;
        }

        // 计时完毕时触发
        @Override
        public void onFinish() {


            if (!mFlag) {

                init_dialog();

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        if (!mFlags) {

                            startActivity(new Intent(Activity_TabLayouyt.this, Activity_HomePage.class));

                        }

                    }
                }, 2000);

            } else {

                startActivity(new Intent(Activity_TabLayouyt.this, Activity_HomePage.class));

            }
            Toast.makeText(context, "喜欢你都那么久那么久了", Toast.LENGTH_LONG).show();

             /*context.startActivity(new Intent(context, MainActivity.class));*/
        }

        // 计时过程显示
        @Override
        public void onTick(long millisUntilFinished) {

        }


    }

    private void init_dialog() {

        mFlag = true;

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Activity_TabLayouyt.this);
        alertDialogBuilder.setTitle("喜欢你都那么久那么久了");//设置标题
        alertDialogBuilder.setMessage("喜欢你的原因，并不是你长的好不好看的原因。而是在特殊的时间给我不一样的感觉"); //设置内容
        alertDialogBuilder.setIcon(R.mipmap.ic_launcher);   //自定义图标
        alertDialogBuilder.setCancelable(false);           //设置是否能点击，对话框的其他区域取消

        alertDialogBuilder.setPositiveButton("确认", new DialogInterface.OnClickListener() {     //设置其确认按钮和监听事件
            @Override
            public void onClick(DialogInterface dialog, int which) {
                new Handler(getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {

                        backMain2.start();

                        mFlags = true;

                    }
                });

            }
        });

        alertDialogBuilder.create();       //创建对话框
        alertDialogBuilder.show();         //显示对话框

    }

}
